var allLinks = [];				//This is a list of all the links in the current tab
var visibleLinks = [];			//This is a list of all the links we want to display in the current tab

// Display all visible links.
function displayLinks() {
	
	//Fetch elements where id is links
	var linksTable = document.getElementById('links');
	while (linksTable.children.length > 1) {
		linksTable.removeChild(linksTable.children[linksTable.children.length - 1])
	}
	
	//Iterate through the list of links
	for (var i = 0; i < visibleLinks.length; ++i) {
		var checkbox = document.createElement('input');		//Create a checkbox for each link
		var row = document.createElement('tr');				//Row for each link
		var col0 = document.createElement('td');			//Check box for each link
		var col1 = document.createElement('td');			//URL for each link
		
		//Arrange different ids for each checkbox and append it in the correct position
		checkbox.checked = true;
		checkbox.type = 'checkbox';
		checkbox.id = 'check' + i;
		col0.appendChild(checkbox);
		
		//Arrange different URLs in the correct position
		col1.innerText = visibleLinks[i];
		
		//Change the appearance of the url
		col1.style.fontFamily = 'Comic Sans MS';
		col1.style.fontSize = 'small';
		col1.onclick = function() {
			checkbox.checked = !checkbox.checked;
		}
		
		//Arrange checkbox-URL pair in the correct row
		row.appendChild(col0);
		row.appendChild(col1);
		linksTable.appendChild(row);
	}
}

// Toggle the checked state of all visible links.
function toggleAll() {
	var checked = document.getElementById('check_all').checked;
	for (var i = 0; i < visibleLinks.length; ++i) {
		
		//Adding ids for each input
		document.getElementById('check' + i).checked = checked;
	}
}

// open all visible checked links.
function openCheckedLinks() {
	for (var i = 0; i < visibleLinks.length; ++i) {
		if (document.getElementById('check' + i).checked) {
			
			//Create tabs for each URL
			chrome.tabs.create({url: visibleLinks[i]});
		}
	}
	window.close();
}

// Re-filter allLinks into visibleLinks and reshow visibleLinks.
function filterLinks() {
	
	//fetch the filter value
	var filterValue = document.getElementById('filter').value;
	
	//Normal filtering
	if (filterValue.indexOf(' ') == -1) {
		
		//choose the element which match the function
		visibleLinks = allLinks.filter(function(link) {
			
			//returns when it contains filter value
			return (link.indexOf(filterValue) !== -1);
		});
	} 
	
	//Filtering with multiple inputs
	else {
		
		//Fetch each inputs
		var inputs = filterValue.split(' ');
		visibleLinks = allLinks.filter(function(link) {
			
			//Iterate through each input
			for (var i = 0; i < inputs.length; ++i) {
			var input = inputs[i];
			
				//Check if it is a valid input or not
				if (input.length != 0) {
					
					//Reduce the result begin with '-'
					var expected = (input[0] != '-');
					if (!expected) {
						input = input.substr(1);
				        if (input.length == 0) {
				        	continue;
				        }
					}
					var found = (link.indexOf(input) !== -1);
					
					//If they don't match, which means it shouldn't be included
					if (found != expected) {
						return false;
					}
				}
			}
			//Include it in the list
			return true;
	    });
	}
	//Display the current list
	displayLinks();
}

//Adding listener to listen the request for link list (It may be called several times.)
chrome.extension.onRequest.addListener(function(links) {
	for (var index in links) {
		allLinks.push(links[index]);
	}
	
	//Sort the list in alphabetical order
	allLinks.sort();
	visibleLinks = allLinks;
	
	//Display the list
	displayLinks();
});

// Set up event handlers and inject send_links.js into all frames in the active
// tab.
window.onload = function() {
	
	//Choose proper functions to be called
	document.getElementById('filter').onkeyup = filterLinks;
	document.getElementById('check_all').onchange = toggleAll;
	document.getElementById('open0').onclick = openCheckedLinks;
	document.getElementById('open1').onclick = openCheckedLinks;

	//Choose the current window
	chrome.windows.getCurrent(function (currentWindow) {
		
		//Choose the active tab
		chrome.tabs.query({active: true, windowId: currentWindow.id},function(activeTabs) {
			
			//inject the js file to all the frames
			chrome.tabs.executeScript(activeTabs[0].id, {file: 'selectLinks.js', allFrames: true});
		});
	});
};
